package com.zygh.lz.service.impl;


import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.sefonsoft.cloud.govern.service.invoke.ServiceSdk;
import com.sefonsoft.cloud.govern.service.invoke.domain.DataServiceRequestDTO;
import com.sefonsoft.cloud.govern.service.invoke.domain.ServiceRequestFieldDTO;
import com.sefonsoft.cloud.govern.service.invoke.utils.Tools;
import com.zygh.lz.dao.PoliceDataMapper;
import com.zygh.lz.dao.PoliceTypeMapper;
import com.zygh.lz.dao.SectionMapper;
import com.zygh.lz.dao.StaffMapper;
import com.zygh.lz.entity.PoliceData;
import com.zygh.lz.entity.Section;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class PoliceDataService extends ServiceImpl<PoliceDataMapper, PoliceData> {

    @Resource
    private PoliceDataMapper policeDataMapper;
    @Resource
    private PoliceTypeMapper policeTypeMapper;
    @Resource
    private StaffMapper staffMapper;
    @Resource
    private SectionMapper sectionMapper;

    private final Logger log = LoggerFactory.getLogger("GPSServer");

    public final String url = "http://62.64.41.147:19200/data-service/gateway/data-service";
    //public final String url = "http://41.5.253.122:6543/data-service/gateway/data-service";

    private String getManage(@RequestParam(required = false) String nextToken,
                             @RequestParam String startDate,
                             @RequestParam String endDate,
                             @RequestParam String jjdw) throws Exception {
        String userId = "975c7bf2f1a647a6ababd0c6b655b9e7";
        //订阅ID
        String subServiceId = "1303319475851079680";
        //String subServiceId = "1303319908583276544";
        //应用系统标识
        String applicationId = "SYS1059";
        //认证token
        String accessToken = "1303319476161458177";

        // 构造请求参数
        DataServiceRequestDTO req = null;
        int size = 1000;
        //当nextToken不为空时查询参数不生效，请求按照第一次的查询条件执行
        if (Tools.isNull(nextToken)) {
            //构造查询参数
            List<ServiceRequestFieldDTO> params = new ArrayList<ServiceRequestFieldDTO>();
            ServiceRequestFieldDTO dto = new ServiceRequestFieldDTO();
            dto.setFieldCode("jjsj01");//查询字段code，从服务输入参数中获取
            dto.setFieldType("dt");//字段类型，从服务输入参数中获取
            dto.setOperateCode("gte");//操作符号，从服务输入参数中获取
            dto.setFieldValue(startDate);//参数值
            params.add(dto);

            ServiceRequestFieldDTO dto2 = new ServiceRequestFieldDTO();
            dto2.setFieldCode("jjsj01");//查询字段code，从服务输入参数中获取
            dto2.setFieldType("dt");//字段类型，从服务输入参数中获取
            dto2.setOperateCode("lte");//操作符号，从服务输入参数中获取
            dto2.setFieldValue(endDate);//参数值
            params.add(dto2);

            ServiceRequestFieldDTO dto3 = new ServiceRequestFieldDTO();
            dto3.setFieldCode("jjdw");//查询字段code，从服务输入参数中获取
            dto3.setFieldType("dt");//字段类型，从服务输入参数中获取
            dto3.setOperateCode("eq");//操作符号，从服务输入参数中获取
            dto3.setFieldValue(jjdw);//参数值
            params.add(dto3);


            if (params.size() <= 0) {
                req = new DataServiceRequestDTO.Builder()
                        .size(size)
                        .includeColumns(true)
                        .build();
            } else {
                req = new DataServiceRequestDTO.Builder()
                        .size(size)
                        .includeColumns(true)
                        .queryFields(params)
                        .build();
            }
        } else {

            //第一次请求时nextToken位空，下次请求从上次请求的结果中获取nextToken
            nextToken = nextToken.replaceAll(" +", "+");

            req = new DataServiceRequestDTO.Builder()
                    .size(size)
                    .nextToken(nextToken)
                    .includeColumns(false).build();
        }

        return ServiceSdk.invoke(url, req, userId, subServiceId, applicationId, accessToken);
    }

    @Async("asyncServiceExecutor")
    public void manager(String startDate, String endDate) {
        long l = System.currentTimeMillis();
        List<Section> sections = sectionMapper.selectList(Wrappers.<Section>lambdaQuery()
                .eq(Section::getSectionPid, 74)
                .isNotNull(Section::getSectionTel)
                .or().eq(Section::getSectionTel, "410100170000"));

        for (Section policeType : sections) {
            try {
                if (StringUtils.isEmpty(startDate)) {
                    PoliceData jjsj01 = policeDataMapper.selectOne(Wrappers.<PoliceData>lambdaQuery()
                            .eq(PoliceData::getJjdw, policeType.getSectionTel())
                            .orderByDesc(PoliceData::getJjsj01).last("limit 1"));
                    startDate = DateUtil.offset(DateUtil.parse(jjsj01.getJjsj01()), DateField.SECOND, +10).toString();
                    endDate = DateUtil.now();
                }

                String result1 = getManage(null, startDate, endDate, policeType.getSectionTel());
                JSONObject jsonObject = JSONObject.fromObject(result1);
                if ("500".equals(jsonObject.get("code").toString())) {
                    return;
                }
                UpdateInsertPolice(result1);
                nextData(result1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        long s = System.currentTimeMillis();
        log.info("接处警数据同步耗时：" + (s - l) + "毫秒");
    }

    public void nextData(String result) throws Exception {
        JSONObject jsonObject = JSONObject.fromObject(result);
        //每次只能取十条
        //token
        Object o = JSONObject.fromObject(jsonObject.get("data")).get("nextToken");
        if (o != null) {
            String token = o.toString();
            String result1 = getManage(token, null, null, null);
            UpdateInsertPolice(result1);
            String list = JSONObject.fromObject(jsonObject.get("data")).get("list").toString();
            List<PoliceData> lists = com.alibaba.fastjson.JSONArray.parseArray(list, PoliceData.class);
            if (lists.size() > 1 && lists.get(0) != null) {
                nextData(result1);
            }
        }


    }


    public void insertPolice(String result) {
        JSONObject jsonObject = JSONObject.fromObject(result);
        JSONArray jsonArray = JSONArray.fromObject(JSONObject.fromObject(jsonObject.get("data")).get("list"));
        List<PoliceData> actionList = new Gson().fromJson(jsonArray.toString(), new TypeToken<List<PoliceData>>() {
        }.getType());
        //判断是否
        if (actionList.get(0) != null && actionList.size() > 1) {
            actionList.forEach(action -> {
                PoliceData policeData = new PoliceData();
                List<Map<String, Object>> staff = staffMapper.findByNames(action.getZpcjr());
                for (Map<String, Object> map : staff) {
                    Section section_pid = sectionMapper.selectByPrimaryKey(Integer.valueOf(map.get("section_pid").toString()));
                    if (section_pid.getSectionTel().equals(action.getCzhdw())) {
                        policeData.setWarningsignal(map.get("staff_num").toString());
                    }
                }
                policeData.setCreatTime(new Date())
                        .setZxdzbz(action.getZxdzbz())
                        .setJjdw(action.getJjdw())
                        .setJjr(action.getJjr())
                        .setJjsj01(action.getJjsj01())
                        .setCjbs(action.getCjbs()).setJjbh110(action.getJjbh110())
                        .setJjygh110(action.getJjygh110()).setJjyxm110(action.getJjyxm110())
                        .setCjdxfsj(action.getCjdxfsj()).setCjdddsj(action.getCjdddsj())
                        .setCjdjssj(action.getCjdjssj()).setCjdecpjsj(action.getCjdecpjsj())
                        .setJqdz110(action.getJqdz110()).setCjlb(action.getCjlb())
                        .setDdxcsj(action.getDdxcsj()).setXzqh(action.getXzqh()).setFsdd(action.getFsdd())
                        .setCdjls(action.getCdjls()).setCdjdcs(action.getCdjdcs()).setWhssje(action.getWhssje())
                        .setJzqzs(action.getJzqzs()).setJzsys(action.getJzsys()).setCzhdw(action.getCzhdw())
                        .setCzhr(action.getCzhr()).setCztxsj(action.getCztxsj()).setCjjg(action.getCjjg())
                        .setCjsj(action.getCjsj()).setXzJqzt(action.getXzJqzt()).setSfzsty(action.getXzJqzt())
                        .setSfzsty(action.getSfzsty()).setSfdxzb(action.getSfdxzb()).setSfdyzb(action.getSfdyzb())
                        .setJsdw(action.getJsdw()).setJsr(action.getJsr()).setCjfksj(action.getCjfksj())
                        .setZpdw(action.getZpdw()).setZpcjr(action.getZpdw()).setZpcjr(action.getZpcjr())
                        .setWbjjr(action.getWbjjr()).setDjdw(action.getDjdw()).setDjr(action.getDjr())
                        .setDjrq(action.getDjrq()).setGabXxrksj(action.getGabXxrksj()).setCjxq(action.getCjxq())
                        .setJcjbh(action.getJcjbh()).setBjnr(action.getBjnr()).setBjsj(action.getBjsj())
                        .setRysss(action.getRysss()).setRysws(action.getRysws());
                policeDataMapper.insert(policeData);

            });
        }

    }


    public void UpdateInsertPolice(String result) {
        log.info("接处警返回结果：" + result);
        JSONObject jsonObject = JSONObject.fromObject(result);
        JSONArray jsonArray = JSONArray.fromObject(JSONObject.fromObject(jsonObject.get("data")).get("list"));
        List<PoliceData> actionList = new Gson().fromJson(jsonArray.toString(), new TypeToken<List<PoliceData>>() {
        }.getType());

        //判断是否能匹配警号
        if (actionList.get(0) != null && actionList.size() > 1) {
            actionList.forEach(action -> {
                PoliceData policeData = new PoliceData();
                List<Map<String, Object>> staff = staffMapper.findByNames(action.getZpcjr());
                if (staff.size() > 0) {
                    for (Map<String, Object> map : staff) {
                        if (map.get("staff_num") != null) {
                            policeData.setWarningsignal(map.get("staff_num").toString());
                        } else {
                            log.info("指派出警人：" + action.getZpcjr());
                        }
                    }
                }

                policeData.setCreatTime(new Date())
                        .setZxdzbz(action.getZxdzbz())
                        .setJjdw(action.getJjdw())
                        .setJjr(action.getJjr())
                        .setJjsj01(action.getJjsj01())
                        .setCjbs(action.getCjbs()).setJjbh110(action.getJjbh110())
                        .setJjygh110(action.getJjygh110()).setJjyxm110(action.getJjyxm110())
                        .setCjdxfsj(action.getCjdxfsj()).setCjdddsj(action.getCjdddsj())
                        .setCjdjssj(action.getCjdjssj()).setCjdecpjsj(action.getCjdecpjsj())
                        .setJqdz110(action.getJqdz110()).setCjlb(action.getCjlb())
                        .setDdxcsj(action.getDdxcsj()).setXzqh(action.getXzqh()).setFsdd(action.getFsdd())
                        .setCdjls(action.getCdjls()).setCdjdcs(action.getCdjdcs()).setWhssje(action.getWhssje())
                        .setJzqzs(action.getJzqzs()).setJzsys(action.getJzsys()).setCzhdw(action.getCzhdw())
                        .setCzhr(action.getCzhr()).setCztxsj(action.getCztxsj()).setCjjg(action.getCjjg())
                        .setCjsj(action.getCjsj()).setXzJqzt(action.getXzJqzt()).setSfzsty(action.getXzJqzt())
                        .setSfzsty(action.getSfzsty()).setSfdxzb(action.getSfdxzb()).setSfdyzb(action.getSfdyzb())
                        .setJsdw(action.getJsdw()).setJsr(action.getJsr()).setCjfksj(action.getCjfksj())
                        .setZpdw(action.getZpdw()).setZpcjr(action.getZpdw()).setZpcjr(action.getZpcjr())
                        .setWbjjr(action.getWbjjr()).setDjdw(action.getDjdw()).setDjr(action.getDjr())
                        .setDjrq(action.getDjrq()).setGabXxrksj(action.getGabXxrksj()).setCjxq(action.getCjxq())
                        .setJcjbh(action.getJcjbh()).setBjnr(action.getBjnr()).setBjsj(action.getBjsj())
                        .setRysss(action.getRysss()).setRysws(action.getRysws());
                policeDataMapper.UpdateInsertPolice(policeData);
                //}


            });
        }

    }


    public void getPersonalInfo() {

    }


}